let axios = require('axios')

// 用promise异步等待，防止对方服务器瘫痪

//设置innertmanyPromise对象,插入许多数据函数
function insertMany(coll, arr) {
    return new Promise((resolve, reject) => {
        let mongodb = require('mongodb').MongoClient;
        let url = "mongodb://localhost:27017";
        mongodb.connect(url, {
            useNewUrlParser: true,
            useUnifiedTopology: true
        }, function (err, db) {
            if (err) {
                throw err;
            }
            var dbb = db.db('local');
            dbb.collection(coll).insertMany(arr, function (err, res) {
                if (err) throw err;
                // console.log('操作成功');
                db.close();
                resolve();
            })
        })
    })
}

//插入一条数据函数
function insertOne(coll, arr) {
    return new Promise((resolve, reject) => {
        let mongodb = require('mongodb').MongoClient;
        let url = "mongodb://localhost:27017";
        mongodb.connect(url, {
            useNewUrlParser: true,
            useUnifiedTopology: true
        }, function (err, db) {
            if (err) {
                throw err;
            }
            var dbb = db.db('local');
            dbb.collection(coll).insertOne(arr, function (err, res) {
                if (err) throw err;
                // console.log('操作成功');
                db.close();
                resolve();
            })
        })
    })
}


//获取英雄列表
async function getHeroList() {
    let httpUrl = 'https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js';
    let result = await axios.get(httpUrl);
    console.log('英雄有了');
    await insertMany('herolist', result.data.hero);
   
    return result.data.hero;
}


//获取英雄介绍
async function getHero(heroid) {
    let httpUrl = `https://game.gtimg.cn/images/lol/act/img/js/hero/${heroid}.js`;
    let result = await axios.get(httpUrl);
    console.log(result.data.hero);
    await insertOne('heroinfo', result.data.hero)
    return result.data;
}

//主函数，获取所有英雄加英雄详情
async function run() {
    let herolist = await getHeroList();
    await herolist.reduce(async (pre, item, i) => {
        await pre;
        return new Promise(async (resolve, reject) => {
            await getHero(item.heroId);
            resolve();
        })
    }, Promise.resolve())
}

run();